package com.daocao.hua.activity;

import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.daocao.hua.R;
import com.daocao.hua.api.callback.VersionContract;
import com.daocao.hua.api.requestInfo.VersionRequest;
import com.daocao.hua.constant.Const;
import com.daocao.hua.model.VersionModel;
import com.daocao.hua.util.FileUtils;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.Dialog;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 2017/9/21.
 */

public class VersionControlActivity extends BaseActivity implements VersionContract.View {
    @BindView(R.id.txt_version)
    TextView txtVersion;
    @BindView(R.id.txt_content)
    TextView txtContent;
    @BindView(R.id.btn_update)
    TextView btnUpdate;
    @BindView(R.id.btn_pingfen)
    TextView btnPingfen;
    private VersionRequest api;
    private Unbinder unbinder;
    private MaterialDialog materialDialog;
    private boolean isShowDialog = false;
    private long lastDownloadId = 0;
    private DownloadBroadcastReceiver receiver;
    private DownloadChangeObserver downloadObserver;
    private DownloadManager manager;
    private String version;
    private int isForce;
    private String downUrl;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.activity_version_control);
        unbinder = ButterKnife.bind(this);
        initBar();
        baseInitView(this, "VersionControlActivity", Const.ViewType.ACTIVITY);
        init();
    }

    private void init() {
        setBackIntent();
        setTitleText("版本更新");
        api = VersionRequest.create();
        api.attachView(this);
        api.getVersion();
    }

    @OnClick({R.id.btn_update, R.id.btn_pingfen})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_update:
                if (TextUtils.isEmpty(version)) {
                    return;
                }
                checkUpdate();
                break;
            case R.id.btn_pingfen:
                goToMarket(this, getPackageName());
                break;
        }
    }


    public void goToMarket(Context context, String packageName) {
        if (!isAvilible(context, "com.tencent.android.qqdownloader")) {
            ToastUtil.makeText(context, "尚未安装应用宝").show();
            return;
        }
        try {
            Uri uri = Uri.parse("market://details?id=" + packageName);
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            goToMarket.setClassName("com.tencent.android.qqdownloader", "com.tencent.pangu.link.LinkProxyActivity");
            context.startActivity(goToMarket);
        } catch (Exception e) {
            Uri uri = Uri.parse("http://sj.qq.com/myapp/detail.htm?apkName=com.daocao.hua");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }

    public boolean isAvilible(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();

        //获取手机系统的所有APP包名，然后进行一一比较
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (((PackageInfo) pinfo.get(i)).packageName
                    .equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {

    }

    @Override
    public void onRequestStart() {

    }


    public void checkUpdate() {
        FileUtils.delFile(Const.APP_NAME); //删除安装包

        String version = this.version;
        String url = downUrl;


        if (TextUtils.isEmpty(version) || TextUtils.isEmpty(url))
            return;

        try {
            String versionName = Util.getVersion(this);
            versionName = versionName.replace("", "");

            String versionNew = version.replace("", "");

            if (compareVersion(versionNew, versionName) > 0) {


                //注册下载监听
                receiver = new DownloadBroadcastReceiver();
                registerReceiver(receiver, new IntentFilter(
                        DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                showInstallDialog();
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private boolean canDownloadState() {
        try {
            int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void showInstallDialog() {
        if (!isShowDialog) {
            isShowDialog = true;
//            String updateContent = PreferenceUtils.getString(this, "upgrade_msg", "");
//            if (updateContent.contains("{current_version}"))
//                updateContent = updateContent.replace("{current_version}", Util.getVersion(this));
//            if (updateContent.contains("{lastest_version}"))
//                updateContent = updateContent.replace("{lastest_version}", PreferenceUtils.getString(this, "lastest_version", "1.0.0"));
            String updateContent = "版本 V" + version;
            if (!Util.isWifi(this))
                updateContent = updateContent + getResources().getString(R.string.update_content);


            String leftBtn;
            if (isForce == 1)
                leftBtn = "";
            else leftBtn = getResources().getString(R.string.update_next_time);

            Dialog.showDefaultDialog(this, getResources().getString(R.string.update_title), updateContent, leftBtn, getResources().getString(R.string.update_now), false, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    isShowDialog = false;
//                    showLoading(true);
                    if (!canDownloadState()) {
                        Dialog.showDefaultDialog(VersionControlActivity.this, getResources().getString(R.string.tip), "请开启下载服务权限", getResources().getString(R.string.cancel), "前往开启", true, new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
                                String packageName = "com.android.providers.downloads";
                                Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.parse("package:" + packageName));
                                startActivity(intent);
                            }

                            @Override
                            public void cancel() {
                                showInstallDialog();
                            }
                        });
                        return;
                    }
                    downloadApp();
                }

                @Override
                public void cancel() {

                }
            });
        }
    }


    private void downloadApp() {
        //判断是否6.0
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    Const.PermissionType.WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        } else {
            initDownloadManager();
        }
    }


    /**
     * 安装app
     *
     * @param myDwonloadID
     */
    private void installApp(long myDwonloadID) {
        try {


            if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
                File file = queryDownloadedApk(this);
                Uri apkUri = FileProvider.getUriForFile(VersionControlActivity.this, "com.daocao.hua.fileprovider", file);
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                startActivity(install);
            } else {
                if (Build.VERSION.SDK_INT >= 23) {

                    Intent install = new Intent(Intent.ACTION_VIEW);
                    File apkFile = queryDownloadedApk(this);
                    install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(install);

                } else {

                    Intent install = new Intent(Intent.ACTION_VIEW);
                    Uri downloadFileUri = manager
                            .getUriForDownloadedFile(myDwonloadID);
                    install.setDataAndType(downloadFileUri,
                            "application/vnd.android.package-archive");
                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(install);

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 安装app 6.0以上
     */
    private void installApp() {
        try {
            Intent install = new Intent(Intent.ACTION_VIEW);
            File apkFile = queryDownloadedApk(this);
            install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(install);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //通过downLoadId查询下载的apk，解决6.0以后安装的问题
    public static File queryDownloadedApk(Context context) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
        long downloadId = PreferenceUtils.getLong(context, "downloadId", 0);
        if (downloadId != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }

    /**
     * 初始化下载
     */
    private void initDownloadManager() {
//        String url = PreferenceUtils.getString(this, "download_url", Const.DOWNLOAD_URL);
        String url = this.downUrl;
        if (TextUtils.isEmpty(url)) return;

        if (materialDialog == null) {
            materialDialog = new MaterialDialog.Builder(this)
                    .title(R.string.update_title)
                    .content(R.string.downloading_text)
                    .progress(false, 100, true)
                    .cancelable(false)
                    .show();
        }

        try {
            manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            Uri uri = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(uri);

            // 设置下载路径和文件名
//        request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, Const.APP_NAMW);
            request.setDestinationInExternalPublicDir("download", Const.APP_NAME);

            request.setDescription(getResources().getString(R.string.app_name)
                    + getResources().getString(R.string.downloading_text));

            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            request.setMimeType("application/vnd.android.package-archive");

            // 设置为可被媒体扫描器找到
            request.allowScanningByMediaScanner();

            // 设置为可见和可管理
            request.setVisibleInDownloadsUi(true);

            lastDownloadId = manager.enqueue(request);

            // 把当前下载的ID保存起来
            PreferenceUtils.putLong(this, "downloadId", lastDownloadId);

            //采用内容观察者模式实现进度
            downloadObserver = new DownloadChangeObserver(null);
            getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);

        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }


    //用于显示下载进度
    class DownloadChangeObserver extends ContentObserver {

        public DownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(lastDownloadId);
            DownloadManager dManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            final Cursor cursor = dManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                final int totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                final int currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                int totalSize = cursor.getInt(totalColumn);
                int currentSize = cursor.getInt(currentColumn);
                float percent = (float) currentSize / (float) totalSize;
                int progress = Math.round(percent * 100);
                p = p + Util.getRandomNum(5, 15);
                if (progress < 80) {
                    if (p > 80) materialDialog.setProgress(80);
                    else
                        materialDialog.setProgress(p);
                } else
                    materialDialog.setProgress(progress);
                if (progress == 100) {
                    materialDialog.setProgress(100);
//                    materialDialog.dismiss();
                }
            }
        }


    }

    private int p = 10;

    public class DownloadBroadcastReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {

            try {


                long myDwonloadID = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                long refernece = PreferenceUtils.getLong(context, "downloadId", 0);

                if (refernece == myDwonloadID) {
                    manager = (DownloadManager) context
                            .getSystemService(DOWNLOAD_SERVICE);

//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) installApp();
//                    else
                    installApp(myDwonloadID);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        api.detachView();
        api = null;
        unbinder.unbind();
    }

    @Override
    public void getVersionSuccess(VersionModel item) {
        version = item.data.lastest_version;
        isForce = item.data.forced_upgrade;
        downUrl = item.data.download_url;
        txtVersion.setText("花毛线 V" + item.data.lastest_version);
        StringBuilder builder = new StringBuilder();
        if (item.data.info != null && item.data.info.size() != 0) {
            for (int i = 0; i < item.data.info.size(); i++) {
                builder.append(item.data.info.get(i) + "\n");
            }
            txtContent.setText(builder);
        }
        String versionName = Util.getVersion(this);
        if (compareVersion(version, versionName) > 0) {
            btnUpdate.setText("发现新版本,点击更新");
            btnUpdate.setBackgroundResource(R.drawable.home_btn_bg);
            btnUpdate.setEnabled(true);
        } else {
            btnUpdate.setEnabled(false);
        }
    }
}
